package com.tuyao.WebSocket;

import com.alibaba.fastjson.JSONObject;
import com.tuyao.pojo.Msg;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@ServerEndpoint(value = "/chatroom")
public class WSServPoint {

    //收集session对象
    //set集合不重复所以采用set集合
    //要用静态，如果不加会每个人一个set对象，无法共享
    static Set<Session> set = new HashSet<Session>();
    static List<String>userList = new ArrayList<String>();
    Map<String,String> map;
    private Msg ms;

    @OnOpen
    public void onOpen(Session session) throws UnsupportedEncodingException {
        System.out.println("连接建立成功!");
        String msg = session.getQueryString();
        msg= URLDecoder.decode(msg,"utf-8");
        System.out.println("msg:"+msg);
        map=new HashMap<String ,String>();
        if(msg.contains("&")){
            String[] sts = msg.split("\\&");
            for(String str:sts){
                String[] strs = str.split("=");
                map.put(strs[0],strs[1]);
            }
        }else{
            String[] strs = msg.split("=");
            map.put(strs[0],strs[1]);
        }
        userList.add(map.get("loginName"));

        System.out.println("map:"+map);
        ms = new Msg();
        ms.setType("s");//系统的信息
        ms.setMsgSender("system");
        ms.setMsgDate(new Date());
        ms.setUserList(userList);
        ms.setMsgInfo(map.get("loginName")+"已经上线!");
        String jsonStr = JSONObject.toJSONString(ms);
        set.add(session);
        bordcast(set,jsonStr);
    }


    @OnClose
    public void onClose(Session session) {
        userList.remove(map.get("loginName"));
        ms = new Msg();
        ms.setType("s");//系统的信息
        ms.setMsgSender("system");
        ms.setMsgDate(new Date());
        ms.setUserList(userList);
        ms.setMsgInfo(map.get("loginName")+"已经下线!");
        String jsonStr = JSONObject.toJSONString(ms);
        set.remove(session);
        bordcast(set,jsonStr);
        System.out.println("连接关闭！！");
    }


    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.println("信息接收！！！"+message);
        Msg ms = new Msg();
        ms.setType("p");//普通用户
        ms.setMsgSender(map.get("loginName"));
        ms.setMsgDate(new Date());
        ms.setMsgInfo(message);
        String jsonstr = JSONObject.toJSONString(ms);
        bordcast(set,jsonstr);

    }




    @OnError
    public void onError(Throwable t) throws Throwable {
        System.out.println("系统异常！！");
    }


    public void bordcast(Set<Session> set,String message){
        for(Session s:set){
            try {
                s.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
